//
//  HomeWorkContentTableViewCell.swift
//  BellManage
//
//  Created by Bestsch on 16/6/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit
import AVFoundation

class HomeWorkContentTableViewCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource,AVAudioPlayerDelegate {

    var dic: NSDictionary!
    
    var userTX: UIImageView!
    var userName: UILabel!
    var editTime: UILabel!
    var contentLabel: UILabel!
    var photoCollectionView: UICollectionView!
    var audioImage: UIImageView!
    
    var player: AVAudioPlayer!
    
    var imageArray = NSMutableArray()
    
    let collectionIdentifier = "PicCollectionViewCellIdentifier"
    
    init(dictionary: NSDictionary, reuseIdentifier: String?) {
        super.init(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier)
        
        self.dic = dictionary
        let url = dic.object(forKey: "Url") as! String
        let usertype = dic.object(forKey: "usertype") as! String
        var msg = dic.object(forKey: "Msg") as! String
        msg = msg.removingPercentEncoding!
        var username = dic.object(forKey: "UserName") as! String
        if usertype == "T" {
            username = "\(username)老师"
        }else{
            username = "\(username)家长"
        }
        var userphoto = dic.object(forKey: "userphoto") as! String
        userphoto = userphoto.replacingOccurrences(of: "../..", with: "")
        let edittime = dic.object(forKey: "edittime") as! String
        
        userTX = UIImageView.init(frame: CGRect(x: 20, y: 10, width: 50, height: 50))
        userTX.layer.cornerRadius = 25
        userTX.sd_setImage(with: URL.init(string: "\(server)\(userphoto)"), placeholderImage: UIImage.init(named: "touxiangm"))
        self.contentView.addSubview(userTX)
        
        userName = UILabel.init(frame: CGRect(x: userTX.frame.maxX+10, y: 10, width: screenW - userTX.frame.maxX - 20, height: 30))
        userName.textColor = UIColor.black
        userName.font = UIFont.systemFont(ofSize: 14)
        userName.text = username
        self.contentView.addSubview(userName)
        
        editTime = UILabel.init(frame: CGRect(x: userTX.frame.maxX+10, y: userName.frame.maxY, width: screenW - userTX.frame.maxX - 20, height: 20))
        editTime.textColor = UIColor.lightGray
        editTime.font = UIFont.systemFont(ofSize: 12)
        editTime.text = edittime
        self.contentView.addSubview(editTime)
        
        contentLabel = UILabel.init(frame: CGRect(x: userTX.frame.maxX+10, y: userTX.frame.maxY+10, width: screenW - userTX.frame.maxX - 20, height: getLabelHeight(msg, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - userTX.frame.maxX - 20)))
        contentLabel.textColor = UIColor.darkGray
        contentLabel.font = UIFont.systemFont(ofSize: 14)
        contentLabel.text = msg
        self.contentView.addSubview(contentLabel)
        
        if usertype == "T" {
            userTX.frame = CGRect(x: screenW-70, y: 10, width: 50, height: 50)
            userName.frame = CGRect(x: 10, y: 10, width: screenW - 90, height: 30)
            editTime.frame = CGRect(x: 10, y: userName.frame.maxY, width: screenW-90, height: 20)
            contentLabel.frame = CGRect(x: 20,  y: userTX.frame.maxY+10, width: screenW - 90, height: getLabelHeight(msg, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 90))
            userName.textAlignment = NSTextAlignment.right
            editTime.textAlignment = NSTextAlignment.right
            contentLabel.textAlignment = NSTextAlignment.right
        }
        var height: CGFloat = 70 + getLabelHeight(msg, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - userTX.frame.maxX - 20) + 10
        if url.characters.count == 0{
            //文字
            
        }else if url.hasSuffix(".jpg"){
            //图片
            imageArray.addObjects(from: url.components(separatedBy: "|"))
            photoCollectionView = UICollectionView.init(frame: CGRect(x: 15, y: contentLabel.frame.maxY+10, width: screenW - 30, height: getPicCollectionHeight(imageArray)), collectionViewLayout: photoFlowLayout.init())
            photoCollectionView.backgroundColor = UIColor.clear
            photoCollectionView.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
            photoCollectionView.scrollsToTop = true
            photoCollectionView.delegate = self
            photoCollectionView.dataSource = self
            self.contentView.addSubview(photoCollectionView)
            height += getPicCollectionHeight(imageArray) + 10
        }else if url.hasSuffix(".mp3"){
            //语音
            audioImage = UIImageView.init(frame: CGRect(x: 30, y: contentLabel.frame.maxY+10, width: screenW - 60, height: 40))
            audioImage.image = UIImage.init(named: "voice0")
            audioImage.contentMode = UIViewContentMode.center
            audioImage.clipsToBounds = true
            audioImage.layer.masksToBounds = true
            audioImage.layer.cornerRadius = 25
            audioImage.backgroundColor = UIColor.init(fromHexCode: "eeeeee")
            var images = [UIImage]()
            for i in 1...12 {
                let img=UIImage(named: "voice\(i)")
                images.append(img!)
            }
            audioImage.animationImages = images
            audioImage.animationDuration = 1
            audioImage.isUserInteractionEnabled = true
            let voiceRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(HomeWorkContentTableViewCell.playVoice))
            audioImage.addGestureRecognizer(voiceRecognizer)
            self.contentView.addSubview(audioImage)
            height += 50
        }
        
    }
    
    /**
     播放音频
     */
    func playVoice() {
        var url = dic.object(forKey: "Url") as! String
        url = server + url.replacingOccurrences(of: "../..", with: "")
        let audioData = try? Data.init(contentsOf: URL.init(string: url)!)
        
        
        player = try! AVAudioPlayer.init(data: audioData!)
        player.delegate = self
        player.volume = 0.8
        player.numberOfLoops = 0
        
        //        let channels = player.numberOfChannels
        player.isMeteringEnabled = true
        
        player.updateMeters()
        audioImage.startAnimating()
        player.prepareToPlay()
        player.play()
    }
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        player.stop()
        audioImage.stopAnimating()
    }
    
    // MARK: 附件的图片显示
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PicCollectionViewCell
        cell.backgroundColor = UIColor.white
        var photo = imageArray.object(at: (indexPath as NSIndexPath).row) as! String
        photo = photo.replacingOccurrences(of: "../..", with: "")
        let imageurl = server + priImg + photo + "&width=300&mode=W"
        cell.imageUrl = imageurl
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let imageUrl = dic.object(forKey: "Url") as! String
        let index = String((indexPath as NSIndexPath).row)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
